#include "common.h"

#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "tests/common_test.h"

// 本程序的绝对路径
char *given_by_command;

static void test_readlink(void){
    char buf[PATH_MAX + 1]; // +1 for the null byte
    ssize_t len = readlink("/proc/self/exe", buf, PATH_MAX);
    buf[len]='\0';

    printf("%s\n",buf);
    printf("%s\n",given_by_command);

    assert(!strcmp(buf,given_by_command));
}

  char g_buffer[BUFSIZ] = {0};    //BUFSIZ为默认buffer大小，在stdio.h中定义

static void test_perror(void){
    
    // todo 错误重定向还未完成，还未完成的测试
    

    printf("0.\n");
    
    FILE *fp;

    // setbuf函数具有打开和关闭缓冲机制
    setbuf(stdout, g_buffer);       //标准错误输出重定向到全局缓存区g_buffer
   
    printf("1.\n");
    fp = fopen("this is not a file,this will be error","r+");


    printf("2.\n");
    if (NULL == fp)
    {
        // 下面的输出在错误中是能看到

        // fopen error: No such file or directory
        perror("fopen error");
    }
    
    setbuf(stdout, NULL);        //恢复标准输出到stderr
    
    if(NULL != fp){
        fclose(fp);
    }
    
    //char *ppos3 = strstr(g_buffer,"fopen error: No such file or directory");
    //assert(NULL!=ppos3);
    printf("==>%s\n   %ld   ....", g_buffer, strlen(g_buffer)); 

    TEST_START_INFO;
    TEST_LINE_REPORT_START;
    TEST_END_INFO;
}

int main(int argc, char *argv[]) {
    (void) argc;
    (void) argv;

#ifdef __linux__
    given_by_command=argv[0];
    test_readlink();
#endif

    // test_perror();
   
    return 0;
};